<?php

/**
 * WeEngine System
 *
 * (c) We7Team 2021 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace App\Http\Controllers;

use App\Exceptions\LogicErrorException;
use App\Http\Logic\UserLogic;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController
{
    /**
     * User Login
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request): JsonResponse
    {
        $data = get_validate_data($request);

        $user = User::query()->where('username', $data->get('username'))
            ->first(['id', 'password', 'salt', 'name']);

        if (empty($user)) {
            throw new LogicErrorException('用户不存在!');
        }

        if (UserLogic::makePassword($data->get('password'), $user->salt) !== $user->password) {
            throw new LogicErrorException('账号或密码不正确!');
        }

        session([
            'user_id' => $user->id
        ]);

        return json_success($user->name . '欢迎回来');
    }

    /**
     * Add User
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function add(Request $request): JsonResponse
    {
        $data     = get_validate_data($request);
        $username = $data->get('username');
        $password = $data->get('password');
        $name     = $data->get('name');
        $salt     = UserLogic::makeSalt();
        $password = UserLogic::makePassword($password, $salt);

        User::query()->create([
            'username' => $username,
            'password' => $password,
            'name'     => $name,
            'salt'     => $salt
        ]);

        return json_success('添加成功');
    }

    /**
     * Get users list
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request): JsonResponse
    {
        $page = get_validate_data($request)->get('page', 1);
        $data = User::query()
            ->orderByDesc('created_at')
            ->paginate(10, ['id', 'username', 'name', 'created_at'], 'page', $page);
        return json_success('', $data->toArray());
    }

    /**
     * Edit user info
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function save(Request $request): JsonResponse
    {
        $data = get_validate_data($request);
        $id   = $data->pull('id');

        if ($data->isNotEmpty()) {
            $user = User::query()->find($id);

            if ($data->has('password')) {
                $salt = $user['salt'];
                $data->set('password', UserLogic::makePassword($data->get('password'), $salt));
            }

            $user->fill($data->toArray())->save();
        }

        return json_success('修改成功');
    }

    /**
     * Delete user
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function delete(Request $request): JsonResponse
    {
        $id = get_validate_data($request)->get('id');

        User::query()->where('id', $id)->limit(1)->delete();

        return json_success('删除成功');
    }

    public function logout()
    {
        session()->forget('user_id');
        return json_success('退出成功');
    }
}
